//
//  HESickedCreateOrderViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2021/5/13.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HESickedCreateOrderViewController.h"
#import "HEDocOrderHeadCell.h"
#import "HEDocOrderInfoCell.h"
#import "HEOrderTitleCell.h"
#import "HEOrderPayCell.h"
#import "HECreateOrderResponse.h"
#import "HEWxPayReqModel.h"
#import "HEPayResultResViewController.h"
#import "HEOrderDetailsViewController.h"
#import "HEAddHealthReportViewController.h"
#import "HEDoctorPrivateSignViewController.h"
#import "HETWViewController.h"
#import "HEQRPayView.h"
#import "HEOrderTabBarView.h"
#import "HEReportSelectCell.h"
#import "HEBindUserModel.h"
#import "HEPreferModel.h"
#import "HEPreferPopView.h"
#import "HEReportTitleInputCell.h"

#import "HEDocOrderAddAddressCell.h"
#import "HEBindInputCell.h"
#import "HEAddressViewController.h"
#import "HEDocOrderAddressCell.h"
#import "HETeamModel.h"
#import "HETeamSpecView.h"
#import "HEApplyModel.h"

#import "HEDocOrderTransFeesCell.h"
#import "HETranspFeesModel.h"
#import "HEReceiveAddressModel.h"

@interface HESickedCreateOrderViewController ()<UITableViewDelegate, UITableViewDataSource, HEReportSelectCellDelegate, HEDocOrderAddAddressCellDelegate, HEDocOrderAddressCellDelegate, HERealNameAuthAlterControllerDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray <HEDoctorCommentModel *> *commentList;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

@property (nonatomic, strong) UIButton *bottomView;

@property (nonatomic, strong) HEOrderModel * order;

@property (nonatomic, strong) HEOrderTabBarView *tabbar;

@property (nonatomic, strong) NSMutableArray <HEBindUserModel *> *bindUsers;

@property (nonatomic, strong) GDFiterCellModel *selectPersonModel;
@property (nonatomic, strong) GDFiterCellModel *preferModel;

@property (nonatomic, strong) HEPreferPopView *preferPopView;
@property (nonatomic, strong) HEPreferModel *prefer;


@property (nonatomic, strong) NSMutableArray <HETeamServiceModel *> *sickedServers;
@property (nonatomic, strong) HETeamSpecView *specView;
@property (nonatomic, strong) HETeamServiceModel *selectServerModel;

@property (nonatomic, strong) NSMutableArray <HEApplyModel *> *serverOrgs;

@property (nonatomic, strong) HETranspFeesModel *transpFee;
@property (nonatomic, strong) NSDecimalNumber *preferAfterPrice; // 商品满减优惠后的价格

@end

@implementation HESickedCreateOrderViewController

- (HETranspFeesModel *)transpFee {
    if (!_transpFee) {
        _transpFee = [HETranspFeesModel new];
        _transpFee.transFees = [NSDecimalNumber decimalNumberWithString:@"0"];
    }
    return _transpFee;
}

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPayFailure object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.title = @"确认信息";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:KNotificationPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFialure) name:KNotificationPayFailure object:nil];
    self.preferAfterPrice = [NSDecimalNumber decimalNumberWithString: @"0"];

    [self initUI];
    [self initCell];
    [self initTabBarView];

    [self loadPaydata];
    [self sickedServerData];
    [self loadServerOrgData];
    
    [self sickedVaildReal];
    
    [self loadAddrresData];

}

- (void)sickedVaildReal {
    if (![[UserManager sharedUserManager] getUserInfo].verifyStatus) {
        HERealNameAuthAlterController *vc = [HERealNameAuthAlterController new];
        vc.delegate = self;
        [self.view addSubview:vc.view];
        [self.view bringSubviewToFront:vc.view];
    }
}
 
- (void)initUI {
    CGFloat tabbarHeight = 49 + KSafeTabbarHeight;
    _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight- ZXNavBarHeight - tabbarHeight) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollsToTop = YES;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.backgroundColor = KWhiteColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)initCell {
    // 总段
    _sections = [NSMutableArray array];
    NSMutableArray *classArr = [NSMutableArray array];
        
    // 显示地址
    GDFiterCellModel *addressModel = [GDFiterCellModel new];
    addressModel.cellKlass = HEDocOrderAddressCell.class;
    
    // 添加地址
    GDFiterCellModel *addModel = [GDFiterCellModel new];
    addModel.cellKlass = HEDocOrderAddAddressCell.class;
    
    // 紧急联系人
    GDFiterCellModel *conactModel = [GDFiterCellModel new];
    conactModel.cellKlass = HEOrderTitleCell.class;
    conactModel.leftTitle = @"紧急联系人";
    
    // 姓名
    GDFiterCellModel *nameModel = [GDFiterCellModel new];
    nameModel.cellKlass = HEBindInputCell.class;
    nameModel.leftTitle = @"姓名：";
    nameModel.tableKey = @"bd_name";
    nameModel.placeHolder = @"请输入紧急联系人姓名";
    
    // 手机号码
    GDFiterCellModel *phoneModel = [GDFiterCellModel new];
    phoneModel.cellKlass = HEBindInputCell.class;
    phoneModel.keyboardType = UIKeyboardTypePhonePad;
    phoneModel.leftTitle = @"电话：";
    phoneModel.tableKey = @"bd_phone";
    phoneModel.placeHolder = @"请输入紧急联系人手机号码";
    
    
    // 支付类型
    GDFiterCellModel *payTypeModel = [GDFiterCellModel new];
    payTypeModel.cellKlass = HEDocOrderInfoCell.class;
    payTypeModel.leftTitle = @"支付类型：";
    payTypeModel.cellType = GDFiterCellTypeDoctorOrderItem;
    
    // 规格
    GDFiterCellModel *preferModel = [GDFiterCellModel new];
    preferModel.cellType = GDFiterCellTypeGoodPrefer;
    preferModel.cellKlass = HEReportTitleInputCell.class;
    preferModel.showArrow = YES;
    preferModel.leftTitle = @"规格：";
    preferModel.placeHolder = @"请选择居家医养服务包";
    preferModel.enable = NO;
    preferModel.tableKey = @"pf_title";
    preferModel.contentColor = CPriceColor;
    preferModel.leftFont = DYBlodFont(18);
    preferModel.contentFont = DYBlodFont(18);
    _preferModel = preferModel;
    
    // 交通费用
    GDFiterCellModel *transFeeModel = [GDFiterCellModel new];
    transFeeModel.cellKlass = HEDocOrderTransFeesCell.class;
    transFeeModel.cellType = GDFiterCellTypeGoodTransFeesInfo;
    
   
    // 支付头部
    GDFiterCellModel *headModel = [GDFiterCellModel new];
    headModel.cellKlass = HEOrderTitleCell.class;
    headModel.leftTitle = @"支付方式";
    headModel.cellType = GDFiterCellTypeDoctorOrderHead;

    // 支付
    GDFiterCellModel *paycelModel = [GDFiterCellModel new];
    paycelModel.cellKlass = HEOrderPayCell.class;
    paycelModel.cellType = GDFiterCellTypeOrderPay;

 
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[addressModel, addModel, conactModel, nameModel, phoneModel, payTypeModel, preferModel, preferModel, transFeeModel, headModel, paycelModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
   
    GDFiterCellModel *topModel = nil;
    if (self.formModel.order_addres) {
        topModel = addressModel;
    }else {
        topModel = addModel;
    }
    
    NSMutableArray *sec1 = @[topModel, conactModel, nameModel, phoneModel].mutableCopy;
    NSMutableArray *sec2 = @[payTypeModel, preferModel, transFeeModel].mutableCopy;
    NSMutableArray *sec3 = @[headModel].mutableCopy;
    NSMutableArray *sec4 = @[].mutableCopy;
    
    if (self.comfireModel.orderPayments.count > 0) {
        for (HEPaymentModel *pay in self.comfireModel.orderPayments) {
            GDFiterCellModel *payModel = [GDFiterCellModel new];
            payModel.cellKlass = HEOrderPayCell.class;
            payModel.cellType = GDFiterCellTypeOrderPay;
            [sec4 addObject:payModel];
        }
    }

    [_sections addObject:sec1];
    [_sections addObject:sec2];
    [_sections addObject:sec3];
    [_sections addObject:sec4];
    [_tableView reloadData];
}


#pragma mark - load Data
- (void)loadPaydata {

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:Kpaymentlist parameters:@{@"appSource":@(KAppSource)} success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        
        self.comfireModel.orderPayments = [HEPaymentModel mj_objectArrayWithKeyValuesArray:response.data];
        if (self.comfireModel.orderPayments.count > 0) {
            HEPaymentModel *firstModel = self.comfireModel.orderPayments.firstObject;
            firstModel.isChoose = YES;
            self.formModel.order_payType = firstModel.code;
        }
        
        NSMutableArray *secs = self.sections.lastObject;

        for (HEPaymentModel *pay in self.comfireModel.orderPayments) {
            GDFiterCellModel *payModel = [GDFiterCellModel new];
            payModel.cellKlass = HEOrderPayCell.class;
            payModel.cellType = GDFiterCellTypeOrderPay;
            [secs addObject:payModel];
        }

        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)loadAddrresData {

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KaddressList parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
 
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        NSArray *addrss = [HEReceiveAddressModel mj_objectArrayWithKeyValuesArray:response.data];
 
        for (HEReceiveAddressModel *model in addrss) {
            if (model.defaultStatus) {
                [self selectAddressWithModel: model];
                break;
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
         
    }];
}

- (void)loadTranpFeeData {
    
    if (!self.selectServerModel) {
        return;
    }
    
    if (!self.formModel.order_addres) {
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject: [NSString stringWithFormat:@"%f",self.formModel.order_addres.latitude] forKey:@"lat"];
    [params setObject: [NSString stringWithFormat:@"%f",self.formModel.order_addres.longitude] forKey:@"lng"];
    [params setObject:[NSNumber numberWithLong: self.selectServerModel.serviceId.integerValue] forKey:@"productId"];

    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KtranspFee parameters:params success:^(id  _Nonnull responseObject) {
        
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            self.transpFee = [HETranspFeesModel mj_objectWithKeyValues:response.data];
            self.formModel.od_transFee = self.transpFee;
            [self calcPayPric];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)calcPayPric {
    // 合计 = 商品总计 + 交通费
    NSDecimalNumber *tot = [_preferAfterPrice decimalNumberByAdding: self.transpFee.transFees];
    self.tabbar.totalPrice = [tot keepTwo];
    
//    [self.tableView.fd_keyedHeightCache invalidateAllHeightCache];
    [self.tableView reloadData];
}

- (void)initTabBarView {
    HEOrderTabBarView *tabbar = [[HEOrderTabBarView alloc] initWithFrame:CGRectZero type:HEOrderTabBarViewTypeDefualt];
    tabbar.delegate = self;
    [self.view addSubview:tabbar];
    self.tabbar = tabbar;
    
    [self calcPayPric];
    
    [tabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

- (void)sickedServerData {
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KhomeServiceGoods parameters:@{@"hospital_id": _serviceCategoryId} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];

        self.sickedServers = [HETeamServiceModel mj_objectArrayWithKeyValuesArray:response.data];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)loadServerOrgData {
    if (self.title) {
        return;
    }
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KhomeOrg parameters:@{} success:^(id  _Nonnull responseObject) {
        DLog(@"%@", [responseObject mj_JSONString])
        HEArrayResponse *respone = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        self.serverOrgs = [NSMutableArray arrayWithArray:[HEApplyModel mj_objectArrayWithKeyValuesArray:respone.data]];
 
        for (HEApplyModel *model in self.serverOrgs) {
            if ([model.hospital_id isEqualToString: _serviceCategoryId]) {
                self.title = model.hospital_name;
            }
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - HEOrderTabBarViewDelegate
- (void)submitOrderHandler {
    if (!self.formModel.order_addres) {
        [Dialog toast:@"请添加上门服务地址~" delay:2.0];
        return;
    }
    
    if ([DYTools isBlankString: self.formModel.bd_name]) {
        [Dialog toastBottom:@"请填写紧急联系人姓名"];
        return;
    }
    
    // 判断手机号格式是否正确
    if (![WOValidate valiMobile: self.formModel.bd_phone]) {
         [Dialog toast:@"请输入正确的手机号码" delay:2];
        return;
    }
        
    if (self.formModel.order_payType == nil) {
        [Dialog toast:@"请选择支付方式~" delay:2.0];
        return;
    }
    
    if (!self.selectServerModel) {
        [Dialog toast:@"请选择居家医养服务包~" delay:2.0];
        return;
    }

    [self crateOrder];
}

- (void)crateOrder {
    
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    
    HECreateOrderRequest *request = [HECreateOrderRequest new];
    request.orderType = HEOrderTypeGeneral;
    request.type = HESubmitPreviewTypeByGoodsDetails;
    request.total = 1;
    request.goodsId = _selectServerModel.serviceId;
    request.channel = HEChannelTypeSickedBed;
    request.skuId = [_selectServerModel.outServiceId integerValue];
    request.source = HEOrderSourceTypeiOS;
    request.appSource = KAppSource;
    request.addressId = self.formModel.order_addres.id;
  
    HESickbedExtras *extra = [HESickbedExtras new];
    extra.order_type = HEChannelTypeSickedBed;
     
    HESickbedPramas *sick = [HESickbedPramas new];
    sick.service_addr = [NSString stringWithFormat:@"%@%@", self.formModel.order_addres.KTitleString, self.formModel.order_addres.detailAddress];
    sick.service_addr_id = self.formModel.order_addres.id;
    sick.urgent_rela_name = self.formModel.bd_name;
    sick.urgent_rela_telp = self.formModel.bd_phone;
    sick.hospital_id = self.serviceCategoryId;
    sick.usid = user.id;
    extra.sick = sick;
    request.extras = [extra mj_JSONString];
 
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KgenerateOrder parameters:request success:^(id  _Nonnull responseObject) {

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            HECreateOrderResponse *data = [HECreateOrderResponse mj_objectWithKeyValues:response.data];
            self.order = data.order;
            
            // 发起支付
            if ([self.formModel.order_payType isEqualToString:KWxPayCode]) {
                [self createWxPayRequest:data.order.id];
            }else if ([self.formModel.order_payType isEqualToString:KAliPayCode]) {
                [self createAliPayRequest:data.order.id];
            }else if ([self.formModel.order_payType isEqualToString:KQRPayCode]) {
                [self showQRPay];
            }
            
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark 二维码支付
- (void)showQRPay {
    NSString *token = [[UserManager sharedUserManager] getToken];
    KWeakSelf
    [HEQRPayView showWithURL: [NSString stringWithFormat:@"https://www.honglutec.com/oldPay/codePage.html?appSource=%d&orderId=%ld&payPlatform=%@&token=%@&providerPay=%d", KAppSource, self.order.id, KPayPlatform, token, _order.storeId == 1 ? 0 : 1] cancelBlock:^{
        [weakSelf payFialure];
    }];
}

#pragma mark 请求支付宝支付串
- (void)createAliPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    [dict setValue:KPayPlatform forKey: @"payPlatform"];
    NSString *url = _order.storeId == 1 ? KAliAppPay : KAliAppProPay;
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [[HEPayManager sharedManager] senAliPayRequest:response.data];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
#pragma mark 请求微信支付串
- (void)createWxPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    [dict setValue:KPayPlatform forKey: @"payPlatform"];
    NSString *url = _order.storeId == 1 ? KWxAppPay : KWxAppProPay;

    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters: dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        HEWxPayReqModel *wxModel = [HEWxPayReqModel mj_objectWithKeyValues:[DYTools getContainersObjectFromJsonString:response.data]];
            
        PayReq* req = [[PayReq alloc] init];
        req.partnerId = wxModel.partnerid;
        req.prepayId = wxModel.prepayid;
        req.nonceStr = wxModel.noncestr;
        req.timeStamp = wxModel.timestamp.unsignedIntValue;
        req.package = wxModel.package;
        req.sign = wxModel.sign;
        [WXApi sendReq:req completion:^(BOOL success) {
            if (!success) {
                [Dialog toastBottom:@"支付失败~"];
                [self payFialure];
            }
        }];

    } failure:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - 支付回调
- (void)paySuccess {
        
    // 支付成功，删除订单预览页，跳转到订单详请页
     HEPayResultResViewController *vc = [HEPayResultResViewController new];
      // 删除当前页
     [self.navigationController qmui_pushViewController:vc animated:YES completion:^{
      NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
         int i = 0;
         for (UIViewController *vc in marr) {
             if ([vc isKindOfClass:[HESickedCreateOrderViewController class]]) {
                  [marr removeObject:vc];
                  break;
             }
             i++;
         }
      self.navigationController.viewControllers = marr;
     }];
}

- (void)payFialure {

    // 放弃支付或者支付失败，删除订单预览页，跳转到订单详请页
    HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
    vc.orderId = self.order.id;
     // 删除当前页
    [self.navigationController qmui_pushViewController:vc animated:YES completion:^{
     NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
        int i = 0;
        for (UIViewController *vc in marr) {
            if ([vc isKindOfClass:[HESickedCreateOrderViewController class]]) {
                 [marr removeObject:vc];
                 break;
            }
           i++;
        }
     self.navigationController.viewControllers = marr;
    }];
}



#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.formModel = self.formModel;
    [cell configCellWithModel:_comfireModel fiterModel:fiterModel indexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
 
    if (fiterModel.cellType == GDFiterCellTypeDoctorServer) {
        return 145;
    }
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        cell.formModel = self.formModel;
        [cell configCellWithModel:self.comfireModel fiterModel:fiterModel indexPath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
     GDFiterCellModel *fiterModel = sec[indexPath.row];
    if (fiterModel.cellType == GDFiterCellTypeOrderPay) {
        HEPaymentModel *payModel = self.comfireModel.orderPayments[indexPath.row];
        self.formModel.order_payType = payModel.code;
        [self changeSelectPayType:indexPath.row];
    }else if (fiterModel.cellType == GDFiterCellTypeGoodPrefer) {
        [self.specView show];
    }
}

- (void)changeSelectPayType:(NSInteger)index {
    for (int i = 0; i < self.comfireModel.orderPayments.count; i++) {
        HEPaymentModel *payModel = self.comfireModel.orderPayments[i];
        if (index == i) {
            payModel.isChoose = YES;
        }else {
            payModel.isChoose = NO;
        }
    }
    [_tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    GDFiterCellModel *fiterModel = sec.lastObject;
    
    if (fiterModel.cellType == GDFiterCellTypeOrderPay) {
        return CGFLOAT_MIN;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    return v;
}

 
- (void)changeTabbarView {
 
}

#pragma mark - HEDocOrderAddAddressCellDelegate HEDocOrderAddressCellDelegate
- (void)orderAddAddressSelect {
    [self toSelectAddressVC];
}

- (void)orderSelectAddressSelect {
    [self toSelectAddressVC];
}

- (void)toSelectAddressVC {
    HEAddressViewController *vc = [HEAddressViewController new];
    vc.type = HEAddressIntoTypeToSelect;
    [vc selectAddress:^(HEReceiveAddressModel * _Nonnull model) {
        [self selectAddressWithModel: model];
//        [self initCell];
    }];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)selectAddressWithModel:(HEReceiveAddressModel *)model {
    self.formModel.order_addres = model;

    self.orderRequest.addressId = model.id;
    GDFiterCellModel *addressModel = [GDFiterCellModel new];
    addressModel.cellKlass = HEDocOrderAddressCell.class;
    
    NSMutableArray *sec1 = self.sections[0];
    [sec1 replaceObjectAtIndex:0 withObject:addressModel];
    [self.tableView reloadData];
    
    [self loadTranpFeeData];
}

#pragma mark - HERealNameAuthAlterControllerDelegate
- (void)realnameAuthCancelAction {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - HEReportSelectCellDelegate
- (void)cellSelectHandler:(HEReportSelectCell *)cell index:(NSInteger)index {
    _orderRequest.memberId = self.bindUsers[index].id;
}

 
- (NSMutableArray<HEBindUserModel *> *)bindUsers {
    if (!_bindUsers) {
        _bindUsers = @[].mutableCopy;
    }
    return _bindUsers;
}

- (HEServerComfireModel *)comfireModel {
    if (!_comfireModel) {
        _comfireModel = [HEServerComfireModel new];
        _comfireModel.payParams = @[@"居家医养"];
    }
    return _comfireModel;
}


- (HETeamSpecView *)specView {
   if (!_specView) {
       
       HETeamModel *_teamModel = [HETeamModel new];
       _teamModel.teamName = self.title;
       
       NSMutableArray *allSepec = [NSMutableArray array];

       // 获取不同service
       NSMutableArray *section = @[].mutableCopy;
       NSMutableArray *serviceKeyArr = @[].mutableCopy;
       NSMutableArray *compareArr = [NSMutableArray array];

       for (HETeamServiceModel *attr in _sickedServers) {
           NSString *stype = [NSString stringWithFormat:@"%ld", attr.serviceType];
           if (![serviceKeyArr containsObject: stype]) {
               [serviceKeyArr addObject:stype];
           }
           
           // 组装比较模型
           compareSepecModel *compareM = [[compareSepecModel alloc]init];
           compareM.goodspriceid = [attr.outServiceId integerValue];
           compareM.spec_price = attr.totalFee;
           compareM.spec_pic = attr.serviceIcon;
//            compareM.stock = compareModel.stock;
           compareM.matchStr = attr.serviceName;
           compareM.org_price = attr.baseFee;

           
           [compareArr addObject:compareM];
       }
       
       // 对数组进行排序（升序）
       serviceKeyArr = [serviceKeyArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
           return [obj1 compare:obj2];
       }];
       
       for (NSString *serviceType in serviceKeyArr) {
           NSMutableArray <HETeamServiceModel *>*services = @[].mutableCopy;
           for (HETeamServiceModel *attr in _sickedServers) {
               NSString *stype = [NSString stringWithFormat:@"%ld", attr.serviceType];
               if ([serviceType isEqualToString:stype]) {
                   [services addObject:attr];
               }
           }
           [section addObject:services];
           
           // 转换数据
           SepecModel *goodSpec = [[SepecModel alloc]init];
           
           // head名称赋值
           goodSpec.name_sepec = @"居家医养服务包级别";
            
           NSMutableArray *subSpecArr = @[].mutableCopy;
           for (HETeamServiceModel *attr in services) {
               // 商品id赋值
               goodSpec.id_sepec = [attr.outServiceId integerValue];
               
               // 创建属性
               SepecDetailModel *sepecmodel = NULL;

               sepecmodel = [[SepecDetailModel alloc] initWithName:[NSString stringWithFormat:@"%@",attr.attr_name] font:DYFont(15)];
               sepecmodel.price_sepec = attr.baseFee;
               sepecmodel.id_sepec = attr.outServiceId;
               [subSpecArr addObject:sepecmodel];
           }
           goodSpec.arr_sepec = subSpecArr;

           [allSepec addObject:goodSpec];
       }
       

       HETeamSpecView *seleView = [HETeamSpecView selectSpecViewWithdataArr:allSepec];
       seleView.goods = _teamModel;
       seleView.comparedataArr = compareArr;
       seleView.comfireBtnTitle = @"确 定";
       seleView.enableCancle = NO;
    
       KWeakSelf
       seleView.finishSelectedBlock = ^(SepecDetailModel *model) {
           weakSelf.formModel.pf_title = [NSString stringWithFormat:@"￥%@/%@",[NSDecimalNumber rounding:model.price_sepec afterPoint:1], model.name_sepec];
           [weakSelf.tableView reloadData];
           self.preferAfterPrice = [NSDecimalNumber decimalNumberWithString:model.price_sepec];
           [self calcPayPric];
           for (HETeamServiceModel *attr in self.sickedServers) {
               if ([attr.outServiceId isEqualToString:model.id_sepec]) {
                   self.selectServerModel = attr;
                   break;
               }
           }
           [self loadTranpFeeData];
       };

       _specView = seleView;
   }
   
   return _specView;
}

@end
